package com.chenwb.concurrency.lock;
/**
 * <pre>类名: DeadLock</pre>
 * <pre>描述: 死锁</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/4/2 9:47</pre>
 * <pre>作者: chenwb</pre>
 */
public class DeadLock {

	private static Object left = new Object();
	private static Object right = new Object();

	static class Lock1 implements Runnable {
		//1、不可共享
		//2、不可释放
		//3、不可剥夺
		//4、
		@Override
		public void run() {
			System.out.println("lock1 run");
			try {
				synchronized (left) {
					System.out.println("lock1 获得left");
					Thread.sleep(200);
					synchronized (right) {
						System.out.println("lock1 获得right");
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	static class Lock2 implements Runnable {

		@Override
		public void run() {
			System.out.println("lock2 run");
			try {
				synchronized (right) {
					System.out.println("lock2 获得right");
					synchronized (left) {
						System.out.println("lock2 获得left");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 执行结束之后我们会看到类似输出
	 * lock1 run
	 * lock2 run
	 * lock1 获得Integer类锁
	 * lock2 获得Long类锁
	 * 通过jps 和 jstack命令查找死锁
	 *"Thread-1":
	 *         at com.chenwb.concurrency.lock.DeadLock$Lock2.run(DeadLock.java:34)
	 *         - waiting to lock <0x000000076c903ec8> (a java.lang.Class for java.lang.Integer)
	 *         - locked <0x000000076c903f70> (a java.lang.Class for java.lang.Long)
	 *         at java.lang.Thread.run(Thread.java:748)
	 * "Thread-0":
	 *         at com.chenwb.concurrency.lock.DeadLock$Lock1.run(DeadLock.java:15)
	 *         - waiting to lock <0x000000076c903f70> (a java.lang.Class for java.lang.Long)
	 *         - locked <0x000000076c903ec8> (a java.lang.Class for java.lang.Integer)
	 *         at java.lang.Thread.run(Thread.java:748)
	 *
	 * Found 1 deadlock.
	 * @param args
	 */
	public static void main(String[] args) {
		Thread t1 = new Thread(new Lock1());
		Thread t2 = new Thread(new Lock2());
		t1.setDaemon(true);
		t1.start();
		t2.start();
	}
}
